<template>
	<view class="ai-container">
		<!-- 聊天消息区域 -->
		<scroll-view class="chat-list" scroll-y="true" :scroll-with-animation="true">
			<view v-for="(item, index) in chatList" :key="index" class="message-item">
				<!-- 系统消息 -->
				<view v-if="item.role === 'system'" class="system-msg">
					{{ item.content }}
				</view>

				<!-- 用户消息 -->
				<view v-else-if="item.role === 'user'" class="user-msg">
					<view class="user-bubble">
						{{ item.content }}
					</view>
				</view>

				<!-- AI回复消息 -->
				<view v-else class="ai-msg">
					<!-- 普通聊天 -->
					<view v-if="item.type === 'chat'" class="ai-bubble">
						{{ item.content }}
					</view>

					<!-- 记账参数展示 -->
					<view v-else-if="item.type === 'bookkeeping'" class="bookkeeping-bubble">
						<view class="param-item">
							<text class="param-label">分类：</text>
							<text class="param-value">{{ item.content.category.name }}</text>
						</view>
						<view class="param-item">
							<text class="param-label">账户：</text>
							<text class="param-value">{{ item.content.account.name }}</text>
						</view>
						<view class="param-item">
							<text class="param-label">金额：</text>
							<text class="param-value">¥{{ item.content.amount }}</text>
						</view>
						<view class="param-item">
							<text class="param-label">时间：</text>
							<text class="param-value">{{ formatTime(item.content.transactionTime) }}</text>
						</view>
						<view class="param-item" v-if="item.content.remark">
							<text class="param-label">备注：</text>
							<text class="param-value">{{ item.content.remark }}</text>
						</view>
						<button class="confirm-btn" 
						:class="{ booked: item.isBooked }" 
						:disabled="item.isBooked" 
						@click="bookkeepingHandle(item.content, index)">
							{{ item.isBooked ? '已记账' : '确认记账' }}
						</button>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 输入区域 -->
		<view class="input-area">
			<input class="input-box" v-model="inputContent" placeholder="请输入内容" @confirm="send" />
			<button class="send-btn" @tap="send">发送</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';

// 用户信息
const userInfo = ref({});
// 聊天内容列表
const chatList = ref([]);
// 输入内容
const inputContent = ref('');

onMounted(() => {
	initUserChat(); // 初始化聊天
	getChatHistory(); // 加载本地聊天记录
});

// 初始化聊天
async function initUserChat() {
	try {
		userInfo.value = JSON.parse(uni.getStorageSync('userInfo'));
		const res = await uni.$http.get(`/ai/start/${userInfo.value.openid}`);

		if (res.data.code == 0) {
			uni.$showT('初始化失败...');
			return 0;
		}

		uni.$showT('初始化成功!');

		// 初始化聊天记录
		chatList.value.push({
			role: 'system',
			type: 'chat',
			content: '轻松记账AI，可聊天和帮忙记账',
			timestamp: new Date().getTime()
		});

		scrollToBottom();
	} catch (e) {
		uni.showToast({ title: '初始化失败', icon: 'none' });
	}
}

// 获取聊天记录
function getChatHistory(){
	let chatHis = uni.getStorageSync("chatHistory");
	if(chatHis == ""){
		return 1;
	}
	
	chatList.value = chatHis;
}

// 获取最新账户列表
async function getUserAccount() {
	// 获取当前登录用户信息
	let userInfo = JSON.parse(uni.getStorageSync('userInfo'));

	const res = await uni.$http.get(`/assetAccounts/getAllByUserId/${userInfo.id}`);

	console.log('获取到的资产列表：', res.data);

	// 资金账户为空
	if (res.data.code == 0) {
		uni.$showT(res.data.msg);
		return {};
	}

	// 根据所有资金账户计算出总资产
	for (let item of res.data.data) {
		item.balance = item.balance.toFixed(2);
	}

	// 数据存储起来
	return res.data.data;
}

// 发送消息
async function send() {
	if (!inputContent.value.trim()) return;

	// 获取资产账户列表发送给AI
	let userAccount = await getUserAccount();

	try {
		// 添加用户消息
		chatList.value.push({
			role: 'user',
			type: 'chat',
			content: inputContent.value,
			timestamp: new Date().getTime()
		});
		
		saveChat(); // 持久化聊天记录

		const content = inputContent.value + `,（用户资产账户列表为：${JSON.stringify(userAccount)})`;
		inputContent.value = '';
		scrollToBottom();

		// 发送请求
		const res = await uni.$http.post('/ai/send', {
			openId: userInfo.value.openid,
			question: content
		});

		console.log('AI应答：', res);

		// 处理AI响应
		if (res.data.type === 'chat') {
			chatList.value.push({
				role: 'assistant',
				type: 'chat',
				content: res.data.content,
				timestamp: new Date().getTime()
			});
		} else if (res.data.type === 'bookkeeping') {
			chatList.value.push({
				role: 'assistant',
				type: 'bookkeeping',
				content: res.data.content,
				isBooked: false, // 新增记账状态字段
				timestamp: new Date().getTime()
			});
		}
		saveChat(); // 持久化聊天记录
		scrollToBottom();
	} catch (e) {
		uni.showToast({ title: '发送失败', icon: 'none' });
	}
}

// 确认记账处理
async function bookkeepingHandle(data, index) {
	// 时间处理：当前日期（年月日） + AI返回的时分秒（为用户描述的'早上'，'中午'等可用时间）
	// 因为AI大模型的时间卡在了2023年，没有办法获取到最新时间
	const now = new Date();
	const aiDate = new Date(data.transactionTime);

	const finalTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), aiDate.getHours(), aiDate.getMinutes(), aiDate.getSeconds()).toISOString();

	// 构造参数
	// 获取默认选择的账本ID
	let accountBookId = getBookIdByBookName();

	// 格式化金额为浮点类型
	let amountF = parseFloat(data.amount);

	let billData = {
		userId: userInfo.value.id,
		bookId: accountBookId, // 账本
		accountId: data.account.id, // 资产账户
		categoryId: data.category.id, // 账单分类（图标）,
		amount: amountF, // 金额
		type: data.category.type, // 收入：1 或 支出：2
		remark: data.remark // 备注
	};

	// 调用记账接口
	const addRes = await uni.$http.post('/bills/addBill', billData);
	console.log("res:", addRes);
	if (addRes.data.code == 0) {
		uni.$showT('AI记账失败，请稍后重试');
		return 0;
	}

	// 后置处理
	chatList.value[index].isBooked = true; // 更新对应消息的状态
	saveChat(); // 持久化聊天记录
	uni.$showT('帮你记好啦~');
}

// 根据账本名称获取账本ID
function getBookIdByBookName() {
	// 获取当前已经选择的账本名称
	let bookName = uni.getStorageSync('selectedBook');
	for (let book of uni.getStorageSync('accountBookData')) {
		if (bookName == book.name) {
			return book.id;
		}
	}
	return 0;
}

// 时间格式化
function formatTime(timeStr) {
	const date = new Date(timeStr);
	return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

// 滚动到底部
function scrollToBottom() {
	nextTick(() => {
		const query = uni.createSelectorQuery();
		query.select('.chat-list').boundingClientRect();
		query.exec((res) => {
			if (res[0]) {
				uni.pageScrollTo({
					scrollTop: res[0].height,
					duration: 300
				});
			}
		});
	});
}

// 持久化聊天记录
function saveChat(){
	uni.setStorageSync("chatHistory", chatList.value)
}
</script>

<style lang="scss" scoped>
.confirm-btn {
	/* 原有按钮样式 */
	background-color: #4cd964;
	color: white;
}

.confirm-btn.booked {
	background-color: #cccccc !important;
}

.confirm-btn[disabled] {
	opacity: 1; /* 保持按钮不透明 */
}

.ai-container {
	height: 100vh;
	display: flex;
	flex-direction: column;

	.chat-list {
		flex: 1;
		padding: 20rpx;
		overflow: auto;
	}

	.message-item {
		margin-bottom: 30rpx;

		.system-msg {
			text-align: center;
			color: #999;
			font-size: 24rpx;
			padding: 10rpx;
		}

		.user-bubble,
		.ai-bubble {
			max-width: 70%;
			padding: 20rpx;
			border-radius: 10rpx;
			margin: 10rpx 0;
		}

		.user-msg {
			display: flex;
			justify-content: flex-end;

			.user-bubble {
				background-color: #07c160;
				color: white;
				position: relative;
				right: 20px;
			}
		}

		.ai-msg {
			display: flex;
			justify-content: flex-start;

			.ai-bubble {
				background-color: #fff;
			}

			.bookkeeping-bubble {
				background-color: #fff;
				border: 1rpx solid #eee;
				border-radius: 10rpx;
				padding: 20rpx;
				width: 80%;

				.param-item {
					margin: 10rpx 0;
					font-size: 28rpx;

					.param-label {
						color: #666;
						margin-right: 10rpx;
					}

					.param-value {
						color: #333;
						font-weight: 500;
					}
				}

				.confirm-btn {
					margin-top: 20rpx;
					background-color: #007aff;
					color: white;
					font-size: 26rpx;
					height: 60rpx;
					line-height: 60rpx;
				}
			}
		}
	}

	.input-area {
		display: flex;
		align-items: center;
		padding: 20rpx;
		border-top: 1rpx solid #eee;
		background-color: #fff;

		.input-box {
			flex: 1;
			border: 1rpx solid #ddd;
			border-radius: 50rpx;
			padding: 15rpx 30rpx;
			margin-right: 20rpx;
		}

		.send-btn {
			width: 120rpx;
			height: 70rpx;
			line-height: 70rpx;
			background-color: #07c160;
			color: white;
			font-size: 28rpx;
			border-radius: 35rpx;
		}
	}
}
</style>
